<template>
  <el-dialog
    :title="title"
    v-model="props.params.visible"
    width="1350px"
    append-to-body
    :before-close="cancel"
  >
    <el-form
      :model="addForm"
      ref="addRef"
      :inline="true"
      :rules="addRules"
      label-width="80px"
    >
      <el-form-item label="品牌" prop="brand">
        <el-select
          v-model="addForm.brand"
          filterable
          reserve-keyword
          clearable
          remote
          :remote-method="getItemBrand"
          @change="brandChange"
          default-first-option
          placeholder="请选择品牌"
          style="width: 200px"
        >
          <el-option
            v-for="item in item_brand"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品类目" prop="category">
        <el-select
          v-model="addForm.category"
          filterable
          clearable
          @change="categoryChange"
          placeholder="请选择商品类目"
          style="width: 200px"
        >
          <el-option
            v-for="item in goods_category"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="回收人" prop="recyclePersonId">
        <el-select
          v-model="addForm.recyclePersonId"
          filterable
          style="width: 200px"
          remote
          reserve-keyword
          placeholder="请选择"
          :remote-method="getUserOption"
          @change="handleChooseUser"
          :loading="userLoading"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="回收客户" prop="recycleCustomer">
        <el-input
          v-model="addForm.recycleCustomer"
          placeholder="请输入"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="回收编号" prop="recycleCode">
        <el-input
          v-model="addForm.recycleCode"
          placeholder="请输入"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="打款情况" prop="paymentStatus">
        <el-select
          v-model="addForm.paymentStatus"
          filterable
          @change="paymentStatusChange"
          clearable
          placeholder="请选择打款情况"
          style="width: 200px"
        >
          <el-option
            v-for="item in payment_status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="打款时间" prop="paymentTime">
        <el-date-picker
          style="width: 200px"
          v-model="addForm.paymentTime"
          type="datetime"
          placeholder="打款时间"
          value-format="YYYY-MM-DD HH:mm:ss"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="快递单号" prop="expressNo">
        <el-input
          v-model="addForm.expressNo"
          placeholder="请输入快递单号"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="商品型号" prop="model">
        <el-input
          v-model="addForm.model"
          placeholder="请输入商品型号"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="回收价格" prop="recyclePrice">
        <el-input-number
          v-model="addForm.recyclePrice"
          placeholder="请输入回收价格"
          :min="0"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="商品编码" prop="ref">
        <el-input
          v-model="addForm.ref"
          placeholder="请输入商品编码"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="addForm.remark"
          placeholder="请输入备注"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="商品正面" prop="file">
        <el-upload
          v-model:file-list="fileList"
          ref="upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :limit="1"
          :disabled="params.type === 'edit'"
          :on-exceed="handleExceed"
          accept=".jpg,.png,.jpeg"
          :auto-upload="false"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="商品背面" prop="file">
        <el-upload
          v-model:file-list="fileListBack"
          ref="upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :limit="1"
          :disabled="params.type === 'edit'"
          :on-exceed="handleExceed"
          accept=".jpg,.png,.jpeg"
          :auto-upload="false"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { addItem, updateItem, getItem } from "@/api/system/skesItem";
import { computed, watch, watchEffect } from "vue";
import { optionSelect } from "@/api/system/skesItem";
import { userOptionSelect } from "@/api/system/user";
import { listData } from "@/api/system/dict/data";
import { genFileId } from "element-plus";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
const props = defineProps({
  params: Object,
  visible: Boolean,
});
const emits = defineEmits(["update:visible", "refresh"]);
const { proxy } = getCurrentInstance();

const title = computed(() =>
  props.params.type === "add" ? "新增回收号登记" : "修改回收号登记"
);
const { goods_category, payment_status } = proxy.useDict(
  "goods_category",
  "payment_status"
);
const dateRange = ref([]);
const addForm = ref({
  brand: undefined,
  brandName: undefined,
  model: undefined,
  recyclePrice: undefined,
  paymentStatus: undefined,
  paymentStatusName: undefined,
  cateGory: undefined,
  cateGoryName: undefined,
  ref: undefined,
  remark: undefined,
  recyclePersonId: undefined,
  recyclePerson: undefined,
  recyclePersonName: undefined,
  recycleCustomer: undefined,
  paymentTime: undefined,
  recycleCode: undefined,
});
const addRules = {
  model: [{ required: true, message: "商品型号不能为空", trigger: "blur" }],
  brand: [{ required: true, message: "品牌不能为空", trigger: "blur" }],
  category: [{ required: true, message: "商品类目不能为空", trigger: "blur" }],
  recyclePersonId: [
    { required: true, message: "回收人不能为空", trigger: "blur" },
  ],
  paymentStatus: [
    { required: true, message: "打款情况不能为空", trigger: "blur" },
  ],
  paymentTime: [
    { required: true, message: "打款情况不能为空", trigger: "blur" },
  ],
  recyclePrice: [
    { required: true, message: "回收价格不能为空", trigger: "blur" },
  ],
  ref: [{ required: true, message: "商品编码不能为空", trigger: "blur" }],
};
/** 商品下拉框 */
const remoteLoading = ref(false);
const itemOptions = ref([]);
async function getItemOption(query) {
  if (query) {
    remoteLoading.value = true;
    const { data } = await optionSelect({ queryKey: query });
    itemOptions.value = data.map((i) => {
      const { id, brand, ref: re, recyclePrice, model, expressNo } = i;
      return {
        value: i.id,
        label: `${id},${brand},${re},${recyclePrice},${model},${
          expressNo || ""
        }`,
        brand: brand,
      };
    });
    remoteLoading.value = false;
  }
}
function brandChange(val) {
  try {
    const option = item_brand.value.find((i) => i.value === val);
    addForm.value.brandName = option.label;
  } catch (error) {}
}
getItemOption(" ");

/** 用户下拉框 */
const userLoading = ref(false);
const userOptions = ref([]);
async function getUserOption(query) {
  if (query) {
    userLoading.value = true;
    const { data } = await userOptionSelect({ queryKey: query });
    userOptions.value = data.map((i) => {
      const { userId, nickName, userName } = i;
      return {
        value: i.userId,
        label: `${userId},${nickName},${userName}`,
        userName,
        nickName,
      };
    });
    userLoading.value = false;
  }
}
function handleChooseUser(userId) {
  const { label, userName, nickName } = userOptions.value.find(
    (i) => i.value === userId
  );
  addForm.value.recyclePerson = nickName;
  addForm.value.recyclePersonName = userName;
}
getUserOption(" ");

/** 品牌 */
const brandLoading = ref(false);
const item_brand = ref([]);
async function getItemBrand(query) {
  if (query) {
    brandLoading.value = true;
    let label = "";
    let val = "";
    if (isNaN(query)) {
      label = query;
    } else {
      val = query;
    }
    const { rows } = await listData({
      pageNum: 1,
      pageSize: 10,
      dictType: "item_brand",
      dictValue: val,
      dictLabel: label,
    });
    item_brand.value = rows.map((i) => {
      const { dictValue, dictLabel } = i;
      return {
        value: dictValue,
        label: dictLabel,
      };
    });
    brandLoading.value = false;
  }
}

function categoryChange(val) {
  try {
    const option = goods_category.value.find((i) => i.value === val);
    addForm.value.categoryName = option.label;
  } catch (err) {}
}
function paymentStatusChange(val) {
  try {
    const option = payment_status.value.find((i) => i.value === val);
    addForm.value.paymentStatusName = option.label;
  } catch (err) {}
}
/** 上传图片 */
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const fileList = ref([]);
const fileListBack = ref([]);
const upload = ref();
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
};
const handleExceed = (files) => {
  upload.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload.value.handleStart(file);
};
watch(
  () => props.params.visible,
  (val) => {
    if (val) {
      addForm.value.recyclePersonId = userStore.id;
      addForm.value.recyclePerson = userStore.nickName;
      addForm.value.recyclePersonName = userStore.name;
    }
  }
);
watchEffect(() => {
  const { visible, type } = props.params;
  if (visible && type === "edit") getDetail();
});
/** 获取商品详情 */
function getDetail() {
  getItem(props.params.id).then((response) => {
    const { recyclePersonId, paymentStatus, brand } = response.data;
    addForm.value = {
      ...response.data,
      recyclePersonId: recyclePersonId + "",
      paymentStatus: paymentStatus + "",
    };
    getItemBrand(brand);
    fileList.value[0] = { url: response.data.watchImageUrl };
    fileListBack.value[0] = { url: response.data.watchImageUrlBack };
  });
}
/** 重置表单  */
function reset() {
  dateRange.value = [];
  fileList.value = [];
  fileListBack.value = [];
  proxy.resetForm("addRef");
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["addRef"].validate((valid) => {
    if (valid) {
      if (props.params.type === "add") {
        const formData = new FormData();
        formData.append(
          "files",
          (fileList.value[0] && fileList.value[0].raw) || undefined
        );
        formData.append(
          "files",
          (fileListBack.value[0] && fileListBack.value[0].raw) || undefined
        );
        const keys = Object.keys(addForm.value);
        for (let i of keys) {
          if (addForm.value[i]) {
            formData.append(i, addForm.value[i]);
          }
        }
        addItem(formData).then((response) => {
          proxy.$modal.msgSuccess("新增商品成功");
          emits("refresh");
          cancel();
        });
      } else {
        updateItem(addForm.value).then((response) => {
          proxy.$modal.msgSuccess("修改商品成功");
          emits("refresh");
          cancel();
        });
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  emits("update:visible", false);
  reset();
}
</script>
